package handler

import (
	"github.com/gin-gonic/gin"
	"oct30-hw/cache"
	"oct30-hw/models"
	"oct30-hw/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数能为空",
		})
		return
	}
	var user models.User
	redis_key := "user_login_" + strconv.Itoa(int(user.ID))
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if redisData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登陆失败账号已被封禁",
		})
		return
	}
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败,账号不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if redisData == 2 {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，账号封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return

}
